'use strict';
/**
 * Created by FreezeSoul on 2015/12/13.
 */
define([
        'angular',
        'adConfig',
        'app/modules/roles/define',
        'app/modules/roles/services/roles',
        'app/modules/page/services/page',
        'app/modules/index/services/index',
        'app/modules/folder/services/folder-tree'
    ],
    function (angular, adConfig) {
        angular.module('ad.roles')
            .controller('adPermissionController', ['$scope', '$q', '$uibModalInstance', '_', 'adFolderEditService', 'adPageEditService', 'adIndexEditService', 'adRolesService', 'item'
                , function ($scope, $q, $uibModalInstance, _, folderService, pageService, chartsService, service, item) {
                    $scope.item = item;

                    $scope.isPageLoading = true;

                    $scope.treePageOptions = {
                        nodeChildren: "children",
                        dirSelectable: false,
                        allowDeselect: true,
                        multiSelection: true,
                        isSelectable: function (node) {
                            return node.type !== "folder";
                        },
                        injectClasses: {
                            "iExpanded": "glyphicon glyphicon-chevron-down",
                            "iCollapsed": "glyphicon glyphicon-chevron-right"
                        }
                    };

                    $scope.treePageModels = [];

                    $scope.expandedPageFolders = [];

                    $scope.selectedPages = [];

                    $scope.itemPageSelected = function (node) {
                    };

                    $scope.isIndexLoading = true;

                    $scope.treeIndexOptions = {
                        nodeChildren: "children",
                        dirSelectable: false,
                        allowDeselect: true,
                        multiSelection: true,
                        isSelectable: function (node) {
                            return node.type !== "folder";
                        },
                        injectClasses: {
                            "iExpanded": "glyphicon glyphicon-chevron-down",
                            "iCollapsed": "glyphicon glyphicon-chevron-right"
                        }
                    };

                    $scope.treeIndexModels = [];

                    $scope.expandedIndexFolders = [];

                    $scope.selectedIndexs = [];

                    $scope.itemIndexSelected = function (node) {
                    };


                    $scope.loaPagedFolders = function () {
                        folderService.getFolders(adConfig.pageFolderType).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var rootItemId = adConfig.rootFolderId;
                                var rootItem = {
                                    "name": "页面根目录",
                                    "id": rootItemId,
                                    "type": "folder",
                                    "data": {folder_id: rootItemId},
                                    "children": [],
                                    "parent": {}
                                };
                                $scope.expandedPageFolders.push(rootItem);
                                var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                    var folders = _.filter(obj.data, function (item) {
                                        return item.folder_parent == currentParentId
                                    });
                                    folders = _.sortBy(folders, function (item) {
                                        return item.folder_name
                                    });
                                    _.each(folders, function (folder) {
                                        var currentId = folder.folder_id;
                                        var currentItem = {
                                            "name": folder.folder_name,
                                            "id": folder.folder_id,
                                            "type": "folder",
                                            "data": folder,
                                            "children": [],
                                            "parent": parentFolderItem
                                        };
                                        convertFolderToTreeNode(currentId, currentItem);
                                        $scope.expandedPageFolders.push(currentItem);
                                        parentFolderItem.children.push(currentItem);
                                    });
                                };
                                convertFolderToTreeNode(rootItemId, rootItem);

                                $scope.loadPages(rootItem);

                            }
                        }, function () {
                        });
                    };

                    $scope.loadPages = function (rootItem) {
                        pageService.getPages().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var walkThroughFolders = function (folder) {
                                    var folderId = folder.id;
                                    var pages = _.filter(obj.data, function (item) {
                                        return item.page_folder_id == folderId
                                    });
                                    _.each(pages, function (page) {
                                        page.page_home = page.page_home ? 1 : 0;
                                        var item = {
                                            "name": page.page_name,
                                            "id": page.page_id,
                                            "type": "element",
                                            "data": page,
                                            "children": [],
                                            "parent": folder
                                        };
                                        folder.children.push(item);
                                        var selectedItems = _.where($scope.rolePageItems, {resource_id: page.page_id});
                                        if (selectedItems && selectedItems.length > 0) {
                                            $scope.selectedPages.push(item);
                                        }
                                    });
                                    var childFolders = _.filter(folder.children, function (item) {
                                        return item.type == "folder"
                                    });
                                    _.each(childFolders, function (folder) {
                                        walkThroughFolders(folder);
                                    });
                                };
                                walkThroughFolders(rootItem);

                                $scope.treePageModels.push(rootItem);

                                $scope.isPageLoading = false;
                            }
                        });
                    };

                    $scope.loadIndexFolders = function () {
                        folderService.getFolders(adConfig.chartFolderType).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var rootItemId = adConfig.rootFolderId;
                                var rootItem = {
                                    "name": "指标根目录",
                                    "id": rootItemId,
                                    "type": "folder",
                                    "data": {folder_id: rootItemId},
                                    "children": [],
                                    "parent": {}
                                };
                                $scope.expandedIndexFolders.push(rootItem);
                                var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                    var folders = _.filter(obj.data, function (item) {
                                        return item.folder_parent == currentParentId
                                    });
                                    folders = _.sortBy(folders, function (item) {
                                        return item.folder_name
                                    });
                                    _.each(folders, function (folder) {
                                        var currentId = folder.folder_id;
                                        var currentItem = {
                                            "name": folder.folder_name,
                                            "id": folder.folder_id,
                                            "type": "folder",
                                            "data": folder,
                                            "children": [],
                                            "parent": parentFolderItem
                                        };
                                        convertFolderToTreeNode(currentId, currentItem);
                                        $scope.expandedIndexFolders.push(currentItem);
                                        parentFolderItem.children.push(currentItem);
                                    });
                                };
                                convertFolderToTreeNode(rootItemId, rootItem);

                                $scope.loadCharts(rootItem);
                            }
                        }, function () {
                        });
                    };

                    $scope.loadCharts = function (rootItem) {
                        chartsService.getCharts().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var walkThroughFolders = function (folder) {
                                    var folderId = folder.id;
                                    var charts = _.filter(obj.data, function (item) {
                                        return item.chart_folder_id == folderId
                                    });
                                    _.each(charts, function (chart) {
                                        var item = {
                                            "name": chart.chart_name,
                                            "id": chart.chart_id,
                                            "type": "element",
                                            "data": chart,
                                            "children": [],
                                            "parent": folder
                                        };
                                        folder.children.push(item);
                                        var selectedItems = _.where($scope.roleChartItems, {resource_id: chart.chart_id});
                                        if (selectedItems && selectedItems.length > 0) {
                                            $scope.selectedIndexs.push(item);
                                        }
                                    });
                                    var childFolders = _.filter(folder.children, function (item) {
                                        return item.type == "folder"
                                    });
                                    _.each(childFolders, function (folder) {
                                        walkThroughFolders(folder);
                                    });
                                };
                                walkThroughFolders(rootItem);

                                $scope.treeIndexModels.push(rootItem);

                                $scope.isIndexLoading = false;
                            }
                        });
                    };

                    $scope.ok = function () {
                        var promises = [];

                        var pageIds = _.map(angular.isArray($scope.selectedPages) ? $scope.selectedPages : [].concat($scope.selectedPages), function (page) {
                            return page.id;
                        });
                        var chartIds = _.map(angular.isArray($scope.selectedIndexs) ? $scope.selectedIndexs : [].concat($scope.selectedIndexs), function (index) {
                            return index.id;
                        });

                        promises.push(service.saveResources($scope.item.role_id, adConfig.resourceTypePage, pageIds));
                        promises.push(service.saveResources($scope.item.role_id, adConfig.resourceTypeChart, chartIds));

                        $q.all(promises).then(function (params) {
                            $uibModalInstance.close($scope.item);
                        });
                    };

                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };

                    $scope.loadResources = function () {
                        var promises = [];
                        promises.push(service.queryResources($scope.item.role_id, adConfig.resourceTypePage));
                        promises.push(service.queryResources($scope.item.role_id, adConfig.resourceTypeChart));

                        $q.all(promises).then(function (params) {
                            if (params.length == 2) {
                                var rolePages = angular.fromJson(params[0]);
                                if (rolePages.result == 'success') {
                                    $scope.rolePageItems = rolePages.data;
                                    $scope.loaPagedFolders();
                                }
                                var roleCharts = angular.fromJson(params[1]);
                                if (roleCharts.result == 'success') {
                                    $scope.roleChartItems = roleCharts.data;
                                    $scope.loadIndexFolders();
                                }
                            }
                        });
                    };

                    $scope.loadResources();
                }]);
    });